import createInstance from './create.ts'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'

// createInstance用于创建axios实例
// 接收三个参数，分别是config配置,RequestInterceptor请求拦截器, ResponseInterceptor响应拦截器
const BaseInstance = createInstance({ baseURL: import.meta.env.VITE_BASE_API_URL })
const H5Instance = createInstance(
  {
    baseURL: import.meta.env.VITE_BASE_API_URL_H5,
  },
  [
    {
      onFulfilled: (config: AxiosRequestConfig) => {
        return config
      },
      onRejected: (error) => {
        const errorMsg = error?.message || 'Request Error'
        console.log(errorMsg)
        return Promise.reject(error)
      },
    },
  ],
  [
    {
      onFulfilled: (response: AxiosResponse) => {
        const { data } = response
        return data
      },
      onRejected: (error) => {
        const { response } = error
        // 处理 HTTP 网络错误
        let message = ''
        // HTTP 状态码
        const status = response?.status
        switch (status) {
          case 401:
            message = 'token 失效，请重新登录'
            // 这里可以触发退出的 action
            break
          case 403:
            message = '拒绝访问'
            break
          case 404:
            message = '请求地址错误'
            break
          case 500:
            message = '服务器故障'
            break
          default:
            message = '网络连接故障'
        }
        console.log(message)

        return Promise.reject(error)
      },
    },
  ],
)

export { BaseInstance, H5Instance }
